import time
from selenium.webdriver import ChromeOptions
from selenium.webdriver import Chrome
# 【2】驱动位置服务
from selenium.webdriver.chrome.service import Service
# 【3】选择器
from selenium.webdriver.common.by import By
from fake_useragent import UserAgent

# 【二】创建浏览器对象
# 【1】指定驱动位置
executable_path = "./chromedriver.exe"
service = Service(executable_path=executable_path)
options = ChromeOptions()
# 无痕模式
options.add_argument('--incognito')  # 隐身模式（无痕模式）
# 禁用浏览器自动化提示条
options.add_argument('--disable-blink-features=AutomationControlled')
# 排除启用自动化开关
options.add_experimental_option("excludeSwitches", ["enable-automation"])
# 关闭自动化扩展信息
options.add_experimental_option('useAutomationExtension', False)
# 设置Chrome为正常用户模式
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--no-sandbox')

# 设置Agent
options.add_argument(f'--user-agent="{UserAgent().random}"')
# 【2】创建浏览器对象
browser = Chrome(service=service, options=options)
# 关键：执行CDP命令来隐藏webdriver属性，避免被检测
browser.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {
    "source": """
        Object.defineProperty(navigator, 'webdriver', {
            get: () => undefined
        })
    """
})
# 【三】打开目标网址
# browser.get("https://www.cnblogs.com/")
# # 设置等待时间
# browser.implicitly_wait(5)
# time.sleep(3)
# # 登录按钮
# login_but = browser.find_element(By.XPATH, value='//*[@id="navbar_login_status"]/a[6]')
# login_but.click()
# time.sleep(3)
# # 用户名输入框
# username_input = browser.find_element(By.XPATH, '//*[@id="mat-input-0"]')
# # 密码输入框
# password_input = browser.find_element(By.XPATH, '//*[@id="mat-input-1"]')
# username_input.send_keys("daiyuling123@foxmail.com")
# time.sleep(1)
# password_input.send_keys("dyl20011113")
# time.sleep(1)
# login_but = browser.find_element(By.XPATH, '/html/body/app-root/app-sign-in-layout/div/div/app-sign-in/app-content-container/div/div/div/form/div/button')
# login_but.click()
# time.sleep(3)
# check_but = browser.find_element(By.XPATH, '//*[@id="aliyunCaptcha-checkbox-icon"]')
# check_but.click()
# time.sleep(3)

# 获取cookie
# cookies = browser.get_cookies()
cookies = "_ga=GA1.1.1045504417.1735378551; Hm_lvt_3e5c5598a94c5915f6f1fc74c974df4b=1752741498; _c_WBKFRo=87XkY6ORzqPmgrUMLvc0gcnNIgP4vcgMeyXejw6I; .Cnblogs.AspNetCore.Cookies=CfDJ8G33EJ5dWE5OhU_7yPrjq1_azr5AUzK_DcqCQFsAS8xG47Da-Y_wDacFVajt9V23af_S74ITWGNNJ2SAiZCS3Bhys5THL8ryfb2WxSXv8YgIVAkM49pxmlYY01E19ed1vgpO0i6EbRAQqR9fjbiZctox4CRp_pnzSCG7dabPj0SOkKc6c_Yge3xQaJLFH65udrQBefyAWR91fJLlI2hMB45otOBj25mBVbqjpwVOW7lOQKNKqFZr3-X-tit5yLD7RKyGwevjhuzGgH8Aw-ZU7Okzn_lc6iHtQtHa61TmXS481dYqM-H0gqixtBPu2qg8PoRZYTNJlW-cN4QDonQMXo70cQ4sDIz5tOFTNnSIRHhg_w_QvhaFQirC-tgYW-oTjuQcaS-FOcTRgYtjgUHIvsf5Q2AY5vPXeOmF7nGujRbfp-JXtTx9ndZypkBWMMcD_vCWjqzLa7OF2a3IbUp9eq9H2lMX68GJ0Hf5uBZPQqPzvZSI5zOXEjgWQrqLmJBWgCkp28A0ac6NoJaXcZ6pZPajIz9t57AcKCoj1E5X6Nm-XAC9_gcC-qCHUbS-mHqrvg; .CNBlogsCookie=19B15CBEEB981FDDDF987699CBD922A5C0E9101C14B78C194B4B677CE5E96AA8ECD8DBF313D82C9D64D7979E90DEE3591434A831DC13DC3A902FC7A233B5B31395E33E965469CDEAF68E72423D8A42D269059130; _ga_3Q0DVSGN10=GS2.1.s1761641994$o1$g1$t1761642423$j60$l0$h0; Hm_lvt_866c9be12d4a814454792b1fd0fed295=1760972880,1761117828,1761642003,1761659480; Hm_lpvt_866c9be12d4a814454792b1fd0fed295=1761659480; HMACCOUNT=9F888295D476CF07; .AspNetCore.Antiforgery.b8-pDmTq1XM=CfDJ8G33EJ5dWE5OhU_7yPrjq1_VmeUr5Ih2kXiGeoEieHfNiO0603Rq_k4L35tLTMFmazvWfT__97WwvPmQujewAERG0q4LNLh56goQmuJd95mT-gDAI1Ct26WeEMjE4-CBcUg5ZYhDTxi7GQyA4UeDmg0; _ga_M95P3TTWJZ=GS2.1.s1761659481$o79$g0$t1761659481$j60$l0$h0"

# 解析 Cookie (修复:使用maxsplit=1来正确处理包含=的cookie值)
cookies_dict = {}
for cookie_item in cookies.split(";"):
    cookie_item = cookie_item.strip()
    if "=" in cookie_item:
        # 只分割第一个=号,防止cookie值中的=号被误分割
        name, value = cookie_item.split("=", 1)
        cookies_dict[name] = value

# 先访问网站
browser.get("https://www.cnblogs.com/")
time.sleep(2)

# 添加cookie
for name, value in cookies_dict.items():
    try:
        browser.add_cookie({
            "name": name,
            "value": value,
            "domain": ".cnblogs.com"  # 指定域名
        })
    except Exception as e:
        print(f"添加cookie失败: {name}, 错误: {e}")

# 【关键】刷新页面让cookie生效
browser.refresh()
time.sleep(3)
print("Cookie已添加并刷新页面")
time.sleep(200)
